#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置文件
存储应用的各种设置和常量
"""

import os
import json
from typing import Dict, Any

class Config:
    """配置管理类"""
    
    def __init__(self, config_file: str = "config.json"):
        self.config_file = config_file
        self.default_config = {
            # 界面设置
            "window_width": 1400,
            "window_height": 900,
            "window_x": None,
            "window_y": None,
            
            # 文件路径
            "screenshot_path": "screenshot.png",
            "xml_path": "ui.xml",
            "export_dir": "exports",
            
            # ADB设置
            "adb_path": "adb",
            "adb_timeout": 30,
            
            # 显示设置
            "show_element_bounds": True,
            "highlight_clickable": True,
            "auto_refresh_interval": 0,  # 0表示不自动刷新
            
            # 代码生成设置
            "autojs_code_style": "modern",  # modern, classic
            "include_comments": True,
            "include_error_handling": True,
            
            # 主题设置
            "theme": "default",  # default, dark, light
            "font_size": 10,
            "font_family": "Microsoft YaHei",
            
            # 快捷键设置
            "shortcuts": {
                "refresh": "F5",
                "screenshot": "Ctrl+S",
                "export_xml": "Ctrl+E",
                "copy_code": "Ctrl+C",
                "find_element": "Ctrl+F"
            },
            
            # 最近使用的设备
            "recent_devices": [],
            "last_device": None,
            
            # 插件设置
            "plugins_enabled": True,
            "plugin_dirs": ["plugins"],
            
            # 日志设置
            "log_level": "INFO",
            "log_file": "app.log",
            "log_max_size": 1024 * 1024,  # 1MB
            "log_backup_count": 5
        }
        
        self.config = self.load_config()
    
    def load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    # 合并默认配置，确保所有键都存在
                    merged_config = self.default_config.copy()
                    merged_config.update(config)
                    return merged_config
            else:
                # 创建默认配置文件
                self.save_config(self.default_config)
                return self.default_config
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            return self.default_config
    
    def save_config(self, config: Dict[str, Any] = None):
        """保存配置文件"""
        if config is None:
            config = self.config
        
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存配置文件失败: {e}")
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        return self.config.get(key, default)
    
    def set(self, key: str, value: Any):
        """设置配置值"""
        self.config[key] = value
        self.save_config()
    
    def update(self, updates: Dict[str, Any]):
        """批量更新配置"""
        self.config.update(updates)
        self.save_config()
    
    def reset_to_default(self):
        """重置为默认配置"""
        self.config = self.default_config.copy()
        self.save_config()
    
    def get_window_geometry(self) -> tuple:
        """获取窗口几何信息"""
        width = self.get("window_width", 1400)
        height = self.get("window_height", 900)
        x = self.get("window_x")
        y = self.get("window_y")
        
        if x is not None and y is not None:
            return f"{width}x{height}+{x}+{y}"
        else:
            return f"{width}x{height}"
    
    def set_window_geometry(self, width: int, height: int, x: int = None, y: int = None):
        """设置窗口几何信息"""
        self.set("window_width", width)
        self.set("window_height", height)
        if x is not None:
            self.set("window_x", x)
        if y is not None:
            self.set("window_y", y)
    
    def add_recent_device(self, device_id: str):
        """添加最近使用的设备"""
        recent_devices = self.get("recent_devices", [])
        if device_id in recent_devices:
            recent_devices.remove(device_id)
        recent_devices.insert(0, device_id)
        
        # 保持最多10个设备
        recent_devices = recent_devices[:10]
        self.set("recent_devices", recent_devices)
        self.set("last_device", device_id)
    
    def get_recent_devices(self) -> list:
        """获取最近使用的设备列表"""
        return self.get("recent_devices", [])
    
    def get_last_device(self) -> str:
        """获取最后使用的设备"""
        return self.get("last_device")
    
    def get_shortcut(self, action: str) -> str:
        """获取快捷键"""
        shortcuts = self.get("shortcuts", {})
        return shortcuts.get(action, "")
    
    def set_shortcut(self, action: str, key: str):
        """设置快捷键"""
        shortcuts = self.get("shortcuts", {})
        shortcuts[action] = key
        self.set("shortcuts", shortcuts)

# 全局配置实例
config = Config()

# 常量定义
class Constants:
    """应用常量"""
    
    # 应用信息
    APP_NAME = "安卓UI预览工具"
    APP_VERSION = "1.0.0"
    APP_AUTHOR = "Your Name"
    
    # 文件扩展名
    SCREENSHOT_EXTENSIONS = [".png", ".jpg", ".jpeg"]
    XML_EXTENSIONS = [".xml"]
    JSON_EXTENSIONS = [".json"]
    
    # 支持的Android版本
    MIN_ANDROID_VERSION = "4.4"
    RECOMMENDED_ANDROID_VERSION = "7.0"
    
    # UI元素类型
    ELEMENT_TYPES = {
        "android.widget.Button": "按钮",
        "android.widget.TextView": "文本视图",
        "android.widget.EditText": "编辑框",
        "android.widget.ImageView": "图片视图",
        "android.widget.CheckBox": "复选框",
        "android.widget.RadioButton": "单选按钮",
        "android.widget.Switch": "开关",
        "android.widget.SeekBar": "进度条",
        "android.widget.ListView": "列表视图",
        "android.widget.RecyclerView": "回收视图",
        "android.widget.ScrollView": "滚动视图",
        "android.widget.LinearLayout": "线性布局",
        "android.widget.RelativeLayout": "相对布局",
        "android.widget.FrameLayout": "帧布局",
        "android.widget.ConstraintLayout": "约束布局"
    }
    
    # AutoJS代码模板
    AUTOJS_TEMPLATES = {
        "modern": {
            "click": "text(\"{text}\").findOne().click();",
            "wait_and_click": "waitFor(() => text(\"{text}\").exists());\ntext(\"{text}\").findOne().click();",
            "input": "text(\"{text}\").findOne().setText(\"{input}\");",
            "scroll": "scroll(\"{direction}\");",
            "back": "back();",
            "home": "home();"
        },
        "classic": {
            "click": "text(\"{text}\").findOne().click();",
            "wait_and_click": "while(!text(\"{text}\").exists()){{\n    sleep(1000);\n}}\ntext(\"{text}\").findOne().click();",
            "input": "text(\"{text}\").findOne().setText(\"{input}\");",
            "scroll": "scroll(\"{direction}\");",
            "back": "back();",
            "home": "home();"
        }
    }
    
    # 颜色主题
    THEMES = {
        "default": {
            "bg_color": "#f0f0f0",
            "fg_color": "#000000",
            "accent_color": "#007acc",
            "success_color": "#28a745",
            "warning_color": "#ffc107",
            "error_color": "#dc3545"
        },
        "dark": {
            "bg_color": "#2d2d30",
            "fg_color": "#ffffff",
            "accent_color": "#007acc",
            "success_color": "#28a745",
            "warning_color": "#ffc107",
            "error_color": "#dc3545"
        },
        "light": {
            "bg_color": "#ffffff",
            "fg_color": "#000000",
            "accent_color": "#007acc",
            "success_color": "#28a745",
            "warning_color": "#ffc107",
            "error_color": "#dc3545"
        }
    }
    
    # 日志级别
    LOG_LEVELS = {
        "DEBUG": 10,
        "INFO": 20,
        "WARNING": 30,
        "ERROR": 40,
        "CRITICAL": 50
    }
    
    # 快捷键映射
    SHORTCUT_ACTIONS = {
        "refresh": "刷新界面",
        "screenshot": "保存截图",
        "export_xml": "导出XML",
        "copy_code": "复制代码",
        "find_element": "查找元素"
    } 